//
//  Common.swift
//  eCLINICAL
//
//  Created by tom on 15/11/10.
//  Copyright © 2015年 tusm. All rights reserved.
//

import UIKit
import AudioToolbox
import Foundation

class Common {
    
    
    
    
    
    /////////////////////////audiotool////////
    
    class AudioTool {
        
        static func soundAlert()
        {
            var soundID:SystemSoundID = 0
            //获取声音地址
            let path = NSBundle.mainBundle().pathForResource("alert", ofType: "wav")
            if(path == nil) {return}
            if(!IO.File.IsFileExists(path!)){return}
            //地址转换
            let baseURL = NSURL(fileURLWithPath: path!)
            //赋值
            AudioServicesCreateSystemSoundID(baseURL, &soundID)
            //提醒（同上面唯一的一个区别）
            AudioServicesPlayAlertSound(soundID)
        }
        
        
        /**
         调用系统震动服务
         - returns: 无返回值
         */
        static func VibrationAlert()
        {
            let soundID = SystemSoundID(kSystemSoundID_Vibrate)
            //振动
            AudioServicesPlaySystemSound(soundID)
        }
        
    }
/////////////////////////////////////////////////
    
    class IO {
        //string sql = "SELECT COUNT(*)  as CNT FROM sqlite_master where type='table' and name='attPointSampleEx'";
        
        
        class Directory {
            
            /**
             返回 app documents路径
             
             - returns: string app documnet 路径
             */
            static func getDocumentPath()->String
            {
                return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String
            }
            
            /**
             返回 app resource路径
             
             - returns: string app resource 路径
             */
            static func getResourcePath()->String
            {
                let res=NSBundle.mainBundle().resourcePath
                return res != nil ? res! : ""
            }
            
            /// 确认指定文件目录是否存在
            ///
            /// 参数：无
            /// true为目录存在
            static func IsDirecotryExists(path:String)->Bool
            {
                return NSFileManager.defaultManager().fileExistsAtPath(path)
            }
            
            /// 创建新目录
            ///
            /// :param:path 目录路径 如：/Users/Tom
            /// :returns:void
            static func CreateDirectory(path:String){
                do{
                    try NSFileManager.defaultManager().createDirectoryAtPath(path, withIntermediateDirectories: true, attributes: nil)
                }catch{}
            }
        }
        //////end class directry///////
        class  File:Object {
            /**
             确认指定文件目录是否存在
             
             - parameter path: 文件路径
             - returns: true文件存在,false不存在
             */
            static func IsFileExists(path:String)->Bool
            {
                return NSFileManager.defaultManager().fileExistsAtPath(path)
            }
            
            /// 创建文件添加内容，并指定属性
            ///
            /// :param:path 文件路径
            /// :returns:true=文件创建成功
            static func CreateFile(path:String,nsdata:NSData,atts:[String:AnyObject])->Bool
            {
                return NSFileManager.defaultManager().createFileAtPath(path, contents: nsdata, attributes: atts)
            }
            
            static func GetPlistValue(key:String,plistFileNameWithoutExt:String="config")->AnyObject?
            {
                let path=NSBundle.mainBundle().pathForResource(plistFileNameWithoutExt, ofType: "plist")
                if(path == nil){
                    LogError("plist file is not exists")
                    return nil
                }
                if(IsFileExists(path!) == false) {
                    LogError("plist file is not exists")
                    return nil
                }
                let dic=NSDictionary(contentsOfFile: path!)
                return dic?.valueForKey(key)
            }
        }
    }
    ///////////////////////////////////////
    
    class Net {
        
        class WebService:Object {
            
            static func process(urlString:String,soapMsg:String,params:[String]?,completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)
            {
                
                let session = NSURLSession.sharedSession()
                
                let soapMessage = (params != nil) ? ReplaceAllWithStrings(soapMsg, pars: params!):soapMsg
                
                let url = NSURL(string: urlString)
                var request = NSURLRequest(URL: url!)
                let theRequest = NSMutableURLRequest(URL: url!)
                let msgLength = String(soapMessage.characters.count)
                theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
                theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
                theRequest.HTTPMethod = "POST"
                theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
                request=theRequest.copy() as! NSURLRequest
                let task = session.dataTaskWithRequest(request, completionHandler: completionHandler)
                task.resume()
            }
            
            static func processSYNC(urlString:String,soapMsg:String,params:[String]?,completionHandler: (NSURLResponse?,NSData?,  NSError?) -> Void)
            {
                let soapMessage = (params != nil) ? ReplaceAllWithStrings(soapMsg, pars: params!):soapMsg
                let url = NSURL(string: urlString)
                var request = NSURLRequest(URL: url!)
                let theRequest = NSMutableURLRequest(URL: url!)
                let msgLength = String(soapMessage.characters.count)
                theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
                theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
                theRequest.HTTPMethod = "POST"
                theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
                request=theRequest.copy() as! NSURLRequest
                NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue() , completionHandler: completionHandler)
            }
            
        }
        
    }
    ///////////////////////////////
    
    class Object {
        
        static func LogError(msg:String)
        {
            print(msg)
        }
        
        static func ReplaceAllWithStrings(str:String,pars:[String])->String
        {
            var result:String=str;
            var index=0
            for (var i=0; i<pars.count;i++)
            {
                let p = pars[i]
                let rep="{$\(index)}"
                index++
                if let r=result.rangeOfString(rep)
                {
                    result.replaceRange(r, with: p)
                }
            }
            return result
        }
        
        static func Term(str:String)->String{
            return str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
        }
        
    }
    /////////////////////////////////
    class SQLite:Object {
        
        struct ERROR {
            static var Message:String=""
        }
        
        var dbPath:String
            {
            get{
                return IO.Directory.getDocumentPath().stringByAppendingString("/db.sqlite");
            }
        }
        /**
         执行sql语句
         
         - parameter sql: 需要执行的sql语句
         - parameter args: sql中"?"对应的变量内容
         - returns: true执行成功,false执行失败
         */
        static func exesql(sql:String,args:[AnyObject]?=nil)->Bool
        {
            ERROR.Message=""
            let sqlite=SQLite()
            return sqlite._exesql(sql,args: args)
        }
        static func select(sql:String,args:[AnyObject]?=nil)->NSArray
        {
            ERROR.Message=""
            let sqlite=SQLite()
            return sqlite._select(sql,args: args)
        }
        static func getValue(key:String,dic:AnyObject)->String
        {
            ERROR.Message=""
            let sqlite=SQLite()
            return sqlite._getValue(key,dic: dic)
        }
        
        func _exesql(sql:String,args:[AnyObject]?=nil)->Bool
        {
            let db=FMDatabase(path: dbPath)
            if db.open(){
                let result = db.executeUpdate(sql, withArgumentsInArray: args)
                if db.hadError() {
                    ERROR.Message="errerCode:\(db.lastErrorCode())---errorMessage:\(db.lastErrorMessage())";
                }
                //db.commit()
                db.close()
                return result
            }else{
                ERROR.Message="can not open database"
                return false
            }
        }
        
        func _select(sql:String,args:[AnyObject]?=nil)->NSArray
        {
            let db=FMDatabase(path: dbPath)
            let result=NSMutableArray()
            if db.open(){
                let rs = db.executeQuery(sql, withArgumentsInArray: args)
                if db.hadError() {
                    ERROR.Message="errerCode:\(db.lastErrorCode())---errorMessage:\(db.lastErrorMessage())";
                }
                while rs.next() {
                    let m=NSMutableDictionary()
                    let clns=rs.columnCount()
                    for (var i:Int32=0; i < clns; i++){
                        let clnName=rs.columnNameForIndex(i)
                        let value=rs.stringForColumn(clnName)
                        m[clnName]=value
                    }
                    result.addObject(m)
                }
                db.close()
                return result
            }else{
                ERROR.Message="can not open database"
                return result
            }
        }
        
        func _getValue(key:String,dic:AnyObject)->String
        {
            let res=(dic as! NSMutableDictionary)[key]
            if(res==nil) {
                return ""
            }else{
                return (res?.description!)!
            }
        }
        
    }
    /////////////////////////////////
    
}





// 屏幕大小
let kFrameSize:CGSize = UIScreen.mainScreen().bounds.size

class LoadingView: UIView {
    
    
    var loadingLab:UILabel!
    var mask:UIControl!
    
    var timer:NSTimer!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.alpha = 1
        self.opaque = false
        self.layer.masksToBounds = true;
        self.layer.cornerRadius = 10;
        self.layer.borderColor = UIColor.grayColor().CGColor;
        self.backgroundColor = UIColor.clearColor()
        
        
        let point:CGPoint  = self.center
        self.frame = CGRectMake(point.x-50, point.y-50, 100, 100)
        
        let tmpView = UIView(frame: CGRectMake(0, 0, 100, 100))
        tmpView.backgroundColor = UIColor.blackColor()
        tmpView.alpha = 0.5
        tmpView.layer.masksToBounds = true;
        tmpView.layer.cornerRadius = 10;
        self.addSubview(tmpView)
        //
        let activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        activityIndicator.hidesWhenStopped = true
        activityIndicator.hidden = true
        activityIndicator.startAnimating()
        activityIndicator.center = CGPointMake(50, 50)
        self.addSubview(activityIndicator)
        
        loadingLab = UILabel(frame: CGRectMake(0, 70, 100, 20));
        loadingLab.backgroundColor = UIColor.clearColor();
        loadingLab.textAlignment = NSTextAlignment.Center
        loadingLab.textColor = UIColor.whiteColor()
        loadingLab.font = UIFont.systemFontOfSize(15);
        self.addSubview(loadingLab)
        
        // 添加超时定时器
        timer = NSTimer(timeInterval: 30, target: self, selector: "timerDeadLine", userInfo: nil, repeats: false)
        
    }
    
    class func shareInstance()->LoadingView{
        struct Singleton{
            static var predicate:dispatch_once_t = 0
            static var instance:LoadingView? = nil
        }
        dispatch_once(&Singleton.predicate,{
            Singleton.instance=LoadingView(frame: CGRectZero)
            }
        )
        return Singleton.instance!
    }
    
    func showTitileAndProcess(title:String!="loading",ownerController:AnyObject!,selector:Selector)
    {
        let vc=ownerController as! UIViewController
        showInView(vc.view)
        showTitle(title!)
        ownerController.performSelector(selector, onThread: NSThread.mainThread(), withObject: nil, waitUntilDone: false)
        
    }
    
    func showTitle(title:String) {
        loadingLab.text = title;
    }
    
    
    func showInView(view:UIView) {
        if mask==nil {
            mask = UIControl(frame: UIScreen.mainScreen().bounds)
            mask.backgroundColor = UIColor.clearColor()
            mask.addSubview(self)
            UIApplication.sharedApplication().keyWindow?.addSubview(mask)
            self.center = view.center
            mask.alpha = 1
        }
        mask.hidden = false
        // 添加定时器
        if timer != nil {
            NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
        }
    }
    
    func timerDeadLine(){
        self.hideView()
        LoadingView.makeToast("请求超时")
    }
    
    func hideView() {
        if NSThread.currentThread().isMainThread{
            self.removeView()
        }
        else {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.removeView()
            })
            
        }
    }
    
    func removeView(){
        if mask != nil {
            //            UIView.beginAnimations("animation", context: nil)
            //            UIView.setAnimationDuration(0.2)
            //            UIView.setAnimationDelegate(self)
            //            UIView.setAnimationDidStopSelector("stopAnimation")
            //            UIView.setAnimationDelay(0.1)
            //            self.transform = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(0.5, 0.5))
            //            UIView.commitAnimations()
            //            self.stopAnimation()
            mask.hidden = true
            timer.invalidate()
        }
    }
    
    func stopAnimation(){
        if mask != nil {
            mask.removeFromSuperview()
            mask = nil
        }
    }
    
    ///////////////////////
    class func makeToast(strTitle:String) {
        //        NSThread.sleepForTimeInterval(0.4)
        //        if NSThread.currentThread().isMainThread{
        //            let toastClass:ToastClass = ToastClass(text: strTitle)
        //        }
        //        else {
        //            dispatch_async(dispatch_get_main_queue(), { () -> Void in
        //                let toastClass:ToastClass = ToastClass(text: strTitle)
        //            })
        //        }
        
    }
    
    class func showNetIndicator(){
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }
    
    class func hidenNetIndicator(){
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }
    //    func showTextOnMainThread(strTitle:String) {
    //        var toastClass:ToastClass = ToastClass(text: strTitle)
    //    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }
}

// 显示toast
class ToastClass:NSObject {
    
    var toastSetting:ToastSettingClass!
    var frameMarginSize:CGFloat! = 10
    var frameSize:CGSize = CGSizeMake(kFrameSize.width-40, 60)
    var view:UIView!
    init(text:String) {
        super.init()
        toastSetting = ToastSettingClass()
        let textFont = toastSetting.textFont
        let size:CGSize = self.sizeWithString(text, font: UIFont.systemFontOfSize(textFont))
        
        let label:UILabel = UILabel (frame: CGRectMake(0, 0, size.width, size.height))
        label.text = text
        label.font = UIFont.systemFontOfSize(textFont)
        label.numberOfLines = 0;
        label.textColor = UIColor.whiteColor()
        
        let window:UIWindow = UIApplication.sharedApplication().keyWindow!
        //        if (window.rootViewController!){
        //            var currentViewCtrl:UIViewController = window.rootViewController!
        //        }
        
        
        let v:UIButton = UIButton(frame:CGRectMake(0, 0, size.width + frameMarginSize, size.height + frameMarginSize))
        label.center = CGPointMake(v.frame.size.width / 2, v.frame.size.height / 2);
        v.addSubview(label)
        
        v.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
        v.layer.cornerRadius = 5
        var point:CGPoint = CGPointMake(window.frame.size.width/2, window.frame.size.height/2);
        point = CGPointMake(point.x , point.y + 10);
        v.center = point
        
        window.addSubview(v)
        view = v
        
        v.addTarget(self, action: "hideToast", forControlEvents: UIControlEvents.TouchDown)
        let timer:NSTimer = NSTimer(timeInterval: 1, target: self, selector: "hideToast", userInfo: nil, repeats: false)
        NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
    }
    
    func sizeWithString(string:NSString, font:UIFont)->CGSize {
        //let dic:NSDictionary = NSDictionary(object: font, forKey: NSFontAttributeName)
        let options = NSStringDrawingOptions.TruncatesLastVisibleLine
        let rect:CGRect = string.boundingRectWithSize(frameSize, options:options, attributes: nil, context: nil)
        return rect.size
    }
    
    func hideToast(){
        UIView.animateWithDuration(0.2, animations: {
            () -> ()in
            self.view.alpha = 0
            }, completion: {
                (Boolean) -> ()in
                self.view.removeFromSuperview()
        })
        
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ToastSettingClass:NSObject {
    
    var textFont:CGFloat!
    var duration:CGFloat!
    var position:iToastGravity!
    override init(){
        super.init()
        textFont = 13
        duration = 2
        position = iToastGravity.Center
    }
}


// 枚举类型
enum iToastGravity:Int{
    case Top = 1000001
    case Bottom
    case Center
    func typeName() -> String {
        return "iToastGravity"
    }
}


